package com.lbn.monitor.app.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.EditText;

import com.free.framework.lib.utils.PrefsMgr;
import com.google.gson.Gson;
import com.lbn.monitor.App;
import com.lbn.monitor.R;
import com.lbn.monitor.api.model.User;
import com.lbn.monitor.app.MainActivity;
import com.lbn.monitor.base.AppBaseActivity;
import com.lbn.monitor.util.Constant;
import com.lbn.monitor.widget.Appbar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends AppBaseActivity<LoginPresenter> implements ILoginView {


    @BindView(R.id.user_name)
    EditText userName;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.remember_user)
    CheckBox rememberUser;
    @BindView(R.id.remember_password)
    CheckBox rememberPassword;

    private final String REMEMBER_USER = "REMEMBER_USER";

    private final String REMEMBER_PASSWORD = "REMEMBER_PASSWORD";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        setAppbar(new Appbar(this).setTitle("登录"));
        if (App.isLogin()) {
            MainActivity.startActivity(this);
            finish();
        }
        userName.setText((String)PrefsMgr.get(this,REMEMBER_USER,""));
        password.setText((String)PrefsMgr.get(this,REMEMBER_PASSWORD,""));
    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }


    public static void startActivity(Context context) {
        context.startActivity(new Intent(context, LoginActivity.class));
    }

    @Override
    protected void onPresenterCreated() {
        super.onPresenterCreated();
    }

    public String getUserName() {
        return userName.getText().toString();
    }

    public String getPassword() {
        return password.getText().toString();
    }

    @Override
    public void onLoginSucceed(User user) {
        App.setUser(user);
        PrefsMgr.putAndApply(this, Constant.USER_INFO, new Gson().toJson(user));
        MainActivity.startActivity(this);
        if(rememberUser.isChecked()){
            PrefsMgr.putAndApply(this,REMEMBER_USER,getUserName());
        }else{
            PrefsMgr.remove(this,REMEMBER_USER);
        }

        if(rememberPassword.isChecked()){
            PrefsMgr.putAndApply(this,REMEMBER_USER,getUserName());
            PrefsMgr.putAndApply(this,REMEMBER_PASSWORD,getPassword());
        }else{
            PrefsMgr.remove(this,REMEMBER_PASSWORD);
        }
        finish();
    }

    @OnClick(R.id.login)
    public void onClick() {
        mPresenter.login(getUserName(), getPassword());
    }
}
